﻿namespace DailyFx.UI {
    using System;

    /// <summary>
    ///		Hosts extension methods for <see cref="UIControl"/> .
    /// </summary>
    public static class UIControlExtension
	{
        /// <summary>
        ///		Enables the target if it implements <see cref="IUIStatus"/>, otherwise does nothing.
        /// </summary>
        public static void TryEnableChild ( object target ) 
		{
			var canEnabled = target as IUIStatus;
			if ( canEnabled != null )
				canEnabled.SetEnabled ();
        }

        /// <summary>
        ///		Disables the item if it implements <see cref="IUIStatus"/>, otherwise does nothing.
        /// </summary>
        public static void TryDisableChild (object target, bool close )
		{
            var canDisabled = target as IUIStatus;
			if ( canDisabled  != null )
				canDisabled.SetDisabled( close );
        }

        /// <summary>
        ///		Closes the specified item.
        /// </summary>
        public static void CloseChild ( this IUIConductor conductor, object item)
		{
            conductor.DisableChild( item, true );
        }

        /// <summary>
        ///		Closes the specified item.
        /// </summary>
        public static void CloseChild<T> (this IUIConductor<T> conductor, T item) where T: class 
		{
            conductor.DisableChild ( item, true );
        }

        ///<summary>
        ///		Enables a child whenever the specified parent is enabled .
        ///</summary>
        public static void EnabledWith ( this IUIStatus child, IUIStatus parent)
		{
            EventHandler<UIEnabledEventArgs> handler = (s, e) => child.SetEnabled();
            parent.Enabled += handler;

			EventHandler<UIDisabledEventArgs> handler2 = null ;
			handler2 = (s, e) => 
			{
				if ( e.WasClosed )
				{
					parent.Enabled -= handler;
                    parent.Disabled -= handler2;
                }
			};
            parent.Disabled += handler2;
        }

        ///<summary>
		///		Disables a child whenever the specified parent is disabled .
        ///</summary>
        public static void DisabledWith ( this IUIStatus child, IUIStatus parent ) 
		{
            EventHandler<UIDisabledEventArgs> handler = null;
            handler = (s, e) =>
			{
                child.SetDisabled( e.WasClosed );
                if ( e.WasClosed )
                    parent.Disabled -= handler;
            };
            parent.Disabled += handler;
        }

        ///<summary>
        ///		Enables and Disables a child whenever the specified parent is Enabled or Disabled .
        ///</summary>
        public static void ConductWith <TChild, TParent> ( this TChild child, TParent parent ) 
            where TChild : IUIStatus 
			where TParent : IUIStatus
        {
            child.EnabledWith ( parent );
            child.DisabledWith ( parent );
        }
    }
}